
import 'package:git/git.dart';

Future<List<CommitLog>> getGitLogList(String path) async {
  try {
    if (await GitDir.isGitDir(path)) {
      final gitDir = await GitDir.fromExisting(path);
      final log = await gitDir.runCommand([
        'log',
        '--pretty=format:"_person==%an ; _date==%ad ; _message==%s;"',
        '--date=format:%y-%m-%d %H:%M:%S',
        '--shortstat',
        '--encoding=GBK'
      ]);
      String str = log.stdout;
      List<String> commitStrings = str.trim().split('\n\n');
      return commitStrings
          .map((commitStr) => CommitLog.fromIni(commitStr))
          .toList();
    }else{
      throw  ArgumentError('非Git项目路径');
    }
  // ignore: empty_catches
  } catch (e) {
    throw  ArgumentError('非Git项目路径');
  }
}

class CommitLog {
  String author;
  String date;
  String message;

  CommitLog({
    required this.author,
    required this.date,
    required this.message,
  });

  factory CommitLog.fromIni(String ini) {
    final lines = ini.split(';');
    final date = lines[1].split('==')[1].trim();
    final message = lines[2].split('==')[1].trim();
    final author = lines[0].split('==')[1].trim();
    return CommitLog(
      author: author,
      date: date,
      message: message,
    );
  }

  @override
  String toString() {
    return 'Commit(author: $author,  date: $date, message: $message)';
  }
}
